package com.yq.testmodule.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.Layout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 两端对齐的text view，可以设置最后一行靠左，靠右，居中对齐
 *
 * @author YD
 */
public class AlignTextView2 extends androidx.appcompat.widget.AppCompatTextView {
    private String TAG = getClass().getSimpleName();
    private float textHeight; // 单行文字高度
    private int width; // textView宽度
    private List<String> lines = new ArrayList<String>(); // 分割后的行
    private List<Integer> tailLines = new ArrayList<Integer>(); // 尾行
    private boolean firstCalc = true;  // 初始化计算

    private float lineSpacingMultiplier = 1.0f;
    private float lineSpacingAdd = 0.0f;

    private int originalHeight = 0; //原始高度
    private int originalLineCount = 0; //原始行数
    private int originalPaddingBottom = 0; //原始paddingBottom
    private boolean setPaddingFromMe = false;
    int maxLines = 5;
    private static final String DEFAULT_OPEN_SUFFIX = "...展开";

    public AlignTextView2(Context context) {
        super(context);
        setTextIsSelectable(false);
    }

    public AlignTextView2(Context context, AttributeSet attrs) {
        super(context, attrs);
        setTextIsSelectable(false);

        int[] attributes = new int[]{android.R.attr.lineSpacingExtra, android.R.attr.lineSpacingMultiplier, android.R.attr.maxLines};
        TypedArray arr = context.obtainStyledAttributes(attrs, attributes);
        lineSpacingAdd = arr.getDimensionPixelSize(0, 0);
        lineSpacingMultiplier = arr.getFloat(1, 1.0f);
        maxLines = arr.getInt(2, maxLines);
        originalPaddingBottom = getPaddingBottom();
        arr.recycle();


        Log.e(TAG, "lineSpacingAdd:" + lineSpacingAdd + "\nlineSpacingMultiplier:" + lineSpacingMultiplier + "\nmaxLines:" + maxLines);


    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        lines.clear();
        tailLines.clear();
        //使用替代textview计算原始高度与行数
        String text = getText().toString();
        TextPaint paint = getPaint();
        measureTextViewHeight(text, paint.getTextSize(), getMeasuredWidth() -
                getPaddingLeft() - getPaddingRight());
        //获取行高
        textHeight = 1.0f * originalHeight / originalLineCount;
        //如果设置了最大行数，使用最大行数高度
        if (lines.size() > maxLines) {
            //设置最大高度
            setMeasuredDimension(widthMeasureSpec, (int) (textHeight * maxLines));
        }

    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        //首先进行高度调整
        if (firstCalc) {
            width = getMeasuredWidth();
            setPaddingFromMe = true;
            //调整textview的paddingBottom来缩小底部空白
            setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(),
                    originalPaddingBottom);
            firstCalc = false;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        TextPaint paint = getPaint();
        paint.setColor(getCurrentTextColor());
        paint.drawableState = getDrawableState();

        width = getMeasuredWidth();

        Paint.FontMetrics fm = paint.getFontMetrics();
        float firstHeight = getTextSize() - (fm.bottom - fm.descent + fm.ascent - fm.top);

        int gravity = getGravity();
        if ((gravity & 0x1000) == 0) { // 是否垂直居中
            firstHeight = firstHeight + (textHeight - firstHeight) / 2;
        }

        int paddingTop = getPaddingTop();
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        width = width - paddingLeft - paddingRight;

        for (int i = 0; i < lines.size(); i++) {
            float drawY = i * textHeight + firstHeight;
            String line = lines.get(i);

            if (line.contains("\n")) {
                line = line.replace("\n", "");
            }
            // 绘画起始x坐标

            //根据需求显示展示文字
            if (i == maxLines - 1) {
                //计算需要替换的文字，考虑替换后是否还可以显示全
                int end = line.length() - DEFAULT_OPEN_SUFFIX.length();
                if(end >0){
                    line = line.substring(0, end) + DEFAULT_OPEN_SUFFIX;
                }
                while (width < paint.measureText(line)) {
                    end--;
                    line = line.substring(0, end) + DEFAULT_OPEN_SUFFIX;
                }
            }
            float drawSpacingX = paddingLeft;
            float gap = (width - paint.measureText(line));
            float interval = gap / (line.length() - 1);

            // 绘制最后一行,不用添加间隔
            if (tailLines.contains(i)) {
                interval = 0;
            }
            for (int j = 0; j < line.length(); j++) {
                if (i >= maxLines) {
                    return;
                }
                //给额外添加的文字设置颜色,并记录可点击区域
                if (i == maxLines - 1 && j > line.length() - DEFAULT_OPEN_SUFFIX.length()) {
                    if (mOpenSuffixRect == null) {
                        mOpenSuffixRect = new Rect();
                    }
                    if (j == line.length() - DEFAULT_OPEN_SUFFIX.length() + 1) {
                        mOpenSuffixRect.left = (int) (paint.measureText(line.substring(0, j)) + interval * j);
                    }
                    mOpenSuffixRect.top = (int) (drawY + paddingTop - firstHeight);
                    mOpenSuffixRect.right = width;
                    mOpenSuffixRect.bottom = (int) (mOpenSuffixRect.top + textHeight);
                    paint.setColor(Color.BLUE);
                } else {
                    paint.setColor(getCurrentTextColor());
                }
                float drawX = paint.measureText(line.substring(0, j)) + interval * j;
                canvas.drawText(line.substring(j, j + 1), drawX + drawSpacingX, drawY + paddingTop, paint);
            }
        }
    }

    private Rect mOpenSuffixRect;
    boolean isInOpenSuffixRect = false;

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        //判断是否点击在了 DEFAULT_OPEN_SUFFIX 文字上面
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            isInOpenSuffixRect = isInOpenSuffixRect(event);
            getParent().requestDisallowInterceptTouchEvent(false);
            return true;
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            if (isInOpenSuffixRect) {
                open();
            }
            isInOpenSuffixRect = false;
        }

        return super.onTouchEvent(event);

    }

    private void open() {
        maxLines = Integer.MAX_VALUE;
        requestLayout();
    }

    public boolean isInOpenSuffixRect(MotionEvent event) {
        if (mOpenSuffixRect == null) return false;
        boolean b = mOpenSuffixRect.left <= event.getX() && mOpenSuffixRect.right >= event.getX()
                && mOpenSuffixRect.top <= event.getY() && mOpenSuffixRect.bottom >= event.getY();
        Log.e(TAG, mOpenSuffixRect.left + "," + mOpenSuffixRect.top + "," + mOpenSuffixRect.right + "," + mOpenSuffixRect.bottom + "   [" + event.getX() + "," + event.getY() + "]" + "  " + b);
        return b;
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        firstCalc = true;
        super.setText(text, type);
    }

    @Override
    public void setPadding(int left, int top, int right, int bottom) {
        if (!setPaddingFromMe) {
            originalPaddingBottom = bottom;
        }
        setPaddingFromMe = false;
        super.setPadding(left, top, right, bottom);
    }


    /**
     * 获取文本实际所占高度，辅助用于计算行高,行数
     *
     * @param text        文本
     * @param textSize    字体大小
     * @param deviceWidth 屏幕宽度
     */
    private void measureTextViewHeight(String text, float textSize, int deviceWidth) {
        TextView textView = new TextView(getContext());
        textView.setText(text);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        int widthMeasureSpec = MeasureSpec.makeMeasureSpec(deviceWidth, MeasureSpec.EXACTLY);
        int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        textView.setLineSpacing(lineSpacingAdd, lineSpacingMultiplier);
        textView.measure(widthMeasureSpec, heightMeasureSpec);

        originalLineCount = textView.getLineCount();
        originalHeight = textView.getMeasuredHeight();

        Layout layout = textView.getLayout();
        int start = 0;
        int end;
        //循环遍历打印每一行
        for (int i = 0; i < textView.getLineCount(); i++) {
            end = layout.getLineEnd(i);
            String line = text.substring(start, end); //指定行的内容
            start = end;
            lines.add(line);
            if (line.contains("\n") || textView.getLineCount() - 1 == i) {
                tailLines.add(i);
            }
        }

    }
}